<template>
	<div v-waterMarker class="merak-card merak-container-has-search">
		<searchBar ref="searchRef" custom-class="searchHeaderDaily"
			:placeholder="$t('marking_application_form.detail_serch_placeholder')" v-model="seatchData"
			@search-event="searchBarPost">
			<template #searchForm>
				<div class="modal-content">
					<div class="modal-title"></div>
					<div class="modal—body">
						<el-scrollbar class="search_from_scrollbar">
							<div class="scrollbar-content">
								<!-- 已选参数 组件-->
								<selectedParams v-model="seatchData" label="label" val="value" option-key="options">
								</selectedParams>
								<el-form ref="ruleFormRef" label-position="top" :model="ruleForm">
									<el-row :gutter="40">
										<el-col :span="span">
											<!-- 订单状态 -->
											<el-form-item :label="seatchData.status_goods.label">
												<el-select filterable class="qf_select" popper-class="own_popper"
													:placeholder="$t('merak.placeholder_select')"
													v-model="ruleForm.status_goods">
													<el-option :label="oItem?.label" :value="oItem?.value"
														v-for="oItem in state.factoryNameCertifyOptions.status_list"
														:key="oItem?.value" />
												</el-select>
											</el-form-item>
										</el-col>
										<el-col :span="span">
											<!-- 系统货号 -->
											<el-form-item :label="seatchData.system_sku.label">
												<el-input class="qf_input" type="text" v-model="ruleForm.system_sku" />
											</el-form-item>
										</el-col>
										<el-col :span="span">
											<!-- 商家货号 -->
											<el-form-item :label="seatchData.supplier_sku.label">
												<el-input class="qf_input" type="text"
													v-model="ruleForm.supplier_sku" />
											</el-form-item>
										</el-col>
										<el-col :span="span">
											<!-- 订单号 -->
											<el-form-item :label="seatchData.orders_numbers.label">
												<el-input class="qf_input" type="text"
													v-model="ruleForm.orders_numbers" />
											</el-form-item>
										</el-col>
										<el-col :span="span">
											<!-- 标签中心订单ID -->
											<el-form-item :label="seatchData.ismp_order_id.label">
												<el-input class="qf_input" type="text"
													v-model="ruleForm.ismp_order_id" />
											</el-form-item>
										</el-col>
										<el-col :span="span">
											<!-- 厂家名称(单证) -->
											<el-form-item :label="seatchData.factory_name_certify.label">
												<el-input class="qf_input" type="text"
													v-model="ruleForm.factory_name_certify" />
											</el-form-item>
										</el-col>
									</el-row>
								</el-form>
							</div>
						</el-scrollbar>
					</div>
					<div class="modal-footer">
						<el-button type="default" @click="handleResetSearch">{{ $t("merak.reset") }}</el-button>
						<el-button type="primary" @click="handleSearch">{{ $t("merak.search") }}</el-button>
						<el-button plain type="primary"
							@click="searchRef?.showPlanModal">{{ $t("merak.save_search_scheme") }}</el-button>
					</div>
				</div>
			</template>
		</searchBar>
		<!-- 表格组件 -->
		<div class="merak-table-wrapper">
			<MerakXTable ref="tableRef" v-bind="tablePayload" :batches="tableBatches" :handles="tableHandler"
				:batch-click="handleBatchClick" :handler-click="handleHanderClick" :query-columns="queryColumns"
				:query-data="queryData" @editor-click="handleEditorClick">
				<!-- PDF -->
				<template #pdf="{ row }">
					<div>
						<el-icon>
							<!-- 生成完成 -->
							<Select v-if="row.pdf_status == 2" class="success-icon" />
							<!-- 已删除 -->
							<CloseBold v-if="row.pdf_status == 3 || row.pdf_status == 5" class="error-icon" />
							<!-- 生成，进行中 -->
							<Loading v-if="row.pdf_status == 1 || row.pdf_status == 4" class="success-icon" />
						</el-icon>
					</div>
				</template>
				<!-- 简版PDF -->
				<template #outter_mark="{ row }">
					<div>
						<el-icon>
							<!-- 生成完成 -->
							<Select v-if="row.simple_pdf_status == 2" class="success-icon" />
							<!-- 已删除 -->
							<CloseBold v-if="row.simple_pdf_status == 3 || row.simple_pdf_status == 5"
								class="error-icon" />
							<!-- 生成，进行中 -->
							<Loading v-if="row.simple_pdf_status == 1 || row.simple_pdf_status == 4"
								class="success-icon" />
						</el-icon>
					</div>
				</template>
				<template #custom_slot_name="{ row }">
					<!-- 查看详情 -->
					<el-button type="primary" link @click="quickShowFn(row)">{{$t('merak.detail') }}</el-button>
				</template>
			</MerakXTable>
		</div>
		<!-- 详情弹窗 弹窗中显示表格 -->
		<el-dialog :title="$t('marking_application_form.gtin_data')" v-model="model" style="width: 58%" align-center
			append-to-body @close="closeDialog">
			<el-table class="merak-table-container" width="100%" v-loading="dtTableLoading"
				:data="detailTableObj.table_list" scrollbar-always-on>
				<el-table-column
					:width="flexColumnWidth(index, item, detailTableObj.table_list, detailTableObj.headers)"
					v-for="(item, index) in detailTableObj.headers" :prop="index" :label="item" />
			</el-table>
		</el-dialog>
		<!-- 编辑外唛数量，内唛数量 -->
		<div style="position: absolute">
			<el-dialog v-model="editorState.state" width="600" align-center append-to-body>
				<template #header>
					<div class="editor-title">
						{{ $t("merak.edit") }}「{{ $t(`marking_application_form.${editorState.field}`) }}」</div>
				</template>
				<el-form ref="formRef" label-position="top" :model="editForm">
					<!-- 外唛数量 -->
					<el-form-item :label="$t('marking_application_form.num_pages_sscc')"
						v-if='editorState.field == "num_pages_sscc"'>
						<el-input class="qf_input" type="text" v-number v-model="editForm.num_pages_sscc" />
					</el-form-item>
					<!-- 内唛数量 -->
					<el-form-item :label="$t('marking_application_form.num_pages_km')"
						v-if='editorState.field == "num_pages_km"'>
						<el-input class="qf_input" type="text" v-model="editForm.num_pages_km" />
					</el-form-item>
					<!-- 生产日期 -->
					<el-form-item :label="$t('marking_application_form.production_date_pdf')"
						v-if='editorState.field == "production_date_pdf"'>
						<el-date-picker v-model="editForm.production_date_pdf" type="date" placeholder="请选择"
							style="width: 100%" />
					</el-form-item>
					<!-- 厂家名称(单证) -->
					<el-form-item :label="$t('marking_application_form.factory_name_certify')"
						v-if='editorState.field == "factory_name_certify"'>
						<el-select filterable class="qf_select" popper-class="own_popper"
							:placeholder="$t('merak.placeholder_select')" v-model="editForm.factory_name_certify">
							<el-option :label="oItem?.label" :value="oItem?.value"
								v-for="oItem in state.factoryNameCertifyList.factory_list" :key="oItem?.value" />
						</el-select>
					</el-form-item>
				</el-form>
				<template #footer>
					<el-button @click="editorState.state = false">{{ $t("merak.cancel") }}</el-button>
					<el-button type="primary" @click="handleSave">{{ $t("merak.confirm") }}</el-button>
				</template>
			</el-dialog>
		</div>
	</div>
</template>

<script setup lang="tsx" name="applicationFormDetail">
	import type {
		FormInstance,
		FormRules
	} from "element-plus";
	import {
		reactive,
		computed,
		watch,
		onMounted,
		ref,
		getCurrentInstance
	} from "vue";
	import searchBar from "@/components/SearchBar";
	import MerakXTable, {
		MerakXTableDropdown,
		MerakXTableInstance,
		MerakXTableProps
	} from "@/components/MerakXTable";
	import useDateFormat from "@/hooks/useDateFormat";
	import {
		useGlobalStore
	} from "@/stores/modules/global";
	import selectedParams from "@/components/SearchBar/components/selectedParams.vue";

	import {
		getApplicationFormDetailHead,
		getApplicationFormDetailList,
		getDetailList,
		orderResetAPI,
		regenerateEADAPI,
		updateFactoryAPI,
		getFactoryNameCertifyAPI,
		downloadPdfApi,
	} from "@/api/modules/markingManagement/applicationFromDetail";
	import {
		UserAuthType,
		getUserAuth
	} from "@/api/modules/user";
	import {
		failMsg,
		successMsg,
		confirmWarningMsg,
		moreConfirm
	} from "@/utils/messageUtils";
	import {
		ElMessageBox,
		ElMessage,
		dayjs
	} from "element-plus";
	import MerakStatCard, {
		MerakStatCardInstance,
		MerakStatDataType
	} from "@/components/MerakStatCard";
	import {
		useRoute
	} from "vue-router";
	import {
		ResultEnum
	} from "@/enums/httpEnum";
	import I18n from "@/languages/index";
	import {
		useDefaultStore
	} from "@/stores/modules/default";
	import {
		exportTableApi
	} from "@/api/modules/table";
	const $t = I18n.global.t;

	const defaultStore = useDefaultStore();
	const route = useRoute();
	const tableRef = ref < MerakXTableInstance > ();
	const countryAuth = ref({}); //权限
	const {
		proxy
	} = getCurrentInstance() !;
	const model = ref(false); //新增、编辑弹窗
	const countryId = ref(""); //国家id
	const globalStore = useGlobalStore();
	const span = computed(() => (globalStore.language === "zh" ? 6 : 8));
	const {
		format
	} = useDateFormat();
	//俄语校验
	const russianInput = (rule, value, callback) => {
		const regexPattern = /[йцукенгшщзхъфывапролджэячсмитьбюё .-]{1,}/; //这里是一个简单的正则表达式，匹配字母和数字
		if (!value || !regexPattern.test(value)) {
			return callback(new Error(proxy!.$t("goods_attribute.input_russian_error")));
		}
		callback();
	};

	const rules = reactive({
		manufacturer_county_ru: [{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: "blur"
			}
			// {
			// 	validator: russianInput,
			// 	trigger: 'blur' ,
			// },
		],
		manufacturer_county_cn: [{
			required: true,
			message: proxy!.$t("goods_attribute.require"),
			trigger: "blur"
		}]
	});


	const searchRef = ref();
	const ruleFormRef = ref < FormInstance > ();
	const tableId = ref < FormInstance > ()
	const ruleForm = reactive < Record < string,
		any >> ({
			status_goods: '', // 订单状态
			// 系统货号ID
			system_sku: '', // 系统货号
			supplier_sku: '', // 商家货号
			orders_numbers: '', // 订单号
			ismp_order_id: '', // 标签中心订单ID
			factory_name_certify: '', // 厂家名称单证
		});

	//高级搜索
	const seatchData = computed({
		get: () => {
			const newData = {
				// 标签订单状态
				status_goods: {
					type: "select",
					label: $t('marking_application_form.status_goods'),
					value: ruleForm.status_goods,
					options: state.factoryNameCertifyOptions?.status_list,
				},
				// 系统货号
				system_sku: {
					type: "input",
					label: $t('marking_application_form.system_sku'),
					value: ruleForm.system_sku
				},
				// 商家货号
				supplier_sku: {
					type: "input",
					label: $t('marking_application_form.supplier_sku'),
					value: ruleForm.supplier_sku
				},
				// 订单号
				orders_numbers: {
					type: "input",
					label: $t('marking_application_form.orders_numbers'),
					value: ruleForm.orders_numbers
				},
				// 标签中心订单ID
				ismp_order_id: {
					type: "input",
					label: $t('marking_application_form.ismp_order_id'),
					value: ruleForm.ismp_order_id
				},
				// 厂家名称(单证)
				factory_name_certify: {
					type: "input",
					label: $t('marking_application_form.factory_name_certify'),
					value: ruleForm.factory_name_certify
				},
			};
			return newData;
		},
		set: value => {
			for (let [key, item] of Object.entries(value)) {
				ruleForm[key] = item.value;
			}
		}
	});

	// 查看详情
	const quickShowFn = row => {
		console.log(row);
		model.value = true;
		getDetailTableData(row);
	};

	// 获取详情弹窗表格中的数据
	let detailTableObj = ref < any > ({});
	const dtTableLoading = ref < boolean > (false);
	const getDetailTableData = (row: any) => {
		const params: any = {
			import_company_id: route.query.i_id,
			marking_order_no: row.orders_numbers
		};
		dtTableLoading.value = true;
		getDetailList(params)
			.then(({
				code,
				data
			}) => {
				if (code === ResultEnum.SUCCESS) {
					detailTableObj.value = data;
				}
			})
			.finally(() => {
				dtTableLoading.value = false;
			});
	};

	// 关闭详情弹窗
	const closeDialog = () => {
		detailTableObj.value = {};
	};

	// 自适应表格列宽
	// 自适应表格列宽
	const flexColumnWidth = (str, title, tableData, tableHeader, flag = "max") => {
		// str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
		// flag为可选值，可不传该参数,传参时可选'max'或'equal',默认为'max'
		// flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度。
		str = str + "";
		let columnContent = "";
		if (!tableData || !tableData.length || tableData.length === 0 || tableData === undefined) {
			return;
		}
		if (!str || !str.length || str.length === 0 || str === undefined) {
			return;
		}
		if (flag === "equal") {
			// 获取该列中第一个不为空的数据(内容)
			for (let i = 0; i < tableData.length; i++) {
				if (tableData[i][str].length > 0) {
					// console.log('该列数据[0]:', tableData[0][str])
					columnContent = tableData[i][str];
					break;
				}
			}
		} else {
			// 获取该列中最长的数据(内容)
			let index = 0;
			for (let i = 0; i < tableData.length; i++) {
				if (tableData[i][str] === null) {
					return;
				}
				const now_temp = tableData[i][str] + "";
				const max_temp = tableData[index][str] + "";
				if (now_temp.length > max_temp.length) {
					index = i;
				}
			}
			columnContent = tableData[index][str];
		}

		// 以下分配的单位长度可根据实际需求进行调整
		let flexWidth = 0;
		let flexHeaderWidth = 0;
		for (const char of title) {
			if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z")) {
				// 如果是英文字符，为字符分配8个单位宽度
				flexHeaderWidth += 10;
			} else if (char >= "\u4e00" && char <= "\u9fa5") {
				// 如果是中文字符，为字符分配18个单位宽度
				flexHeaderWidth += 20;
			} else if (/^\d+$/.test(char)) {
				// 其他种类字符，为字符分配8个单位宽度
				flexHeaderWidth += 10;
			} else {
				flexHeaderWidth += 10;
			}
		}
		if (columnContent?.length > 0) {
			for (const char of columnContent) {
				if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z")) {
					// 如果是英文字符，为字符分配8个单位宽度
					flexWidth += 10;
				} else if (char >= "\u4e00" && char <= "\u9fa5") {
					// 如果是中文字符，为字符分配18个单位宽度
					flexWidth += 20;
				} else if (/^\d+$/.test(char)) {
					// 其他种类字符，为字符分配8个单位宽度
					flexWidth += 10;
				} else {
					flexWidth += 10;
				}
			}
		}

		if (flexWidth < 80) {
			// 设置最小宽度
			flexWidth = 80;
		}
		if (flexHeaderWidth < 80) {
			// 设置最小宽度
			flexHeaderWidth = 80;
		}
		if (flexHeaderWidth > flexWidth) {
			return flexHeaderWidth + "px";
		} else {
			return flexWidth + "px";
		}
	};

	// 页面配置数据
	const state = reactive < {
		filterOptions: Array < any > ;
		statValue: string;
		statData: MerakStatDataType[][];
		statParams: Record < string,
		string > ;
		applicationOptionData: Record < string,
		string > ;
		thisPageDate: Record < string,
		string > ;
		factoryNameCertifyList: Record < string,
		string > ;
		factoryNameCertifyOptions: Record < string,
		string > ;
	} > ({
		// 高级搜索方案下拉选项
		filterOptions: [],
		applicationOptionData: {},
		thisPageDate: {
			keyword: "",
			import_company_id: ""
		},
		factoryNameCertifyList: {},
		factoryNameCertifyOptions: {}
	});

	// 动态计算表格的外部筛选数据
	const params = computed(() => ({
		...state.thisPageDate
	}));

	const tableBatches = computed(() => {
		const batchesConfig = {
			// 导出标签数据
			exportLabelData: {
				type: "exportLabelData",
				text: $t('marking_application_form.export_label_data')
			},
			// 生成EAC版PDF
			generateEAC: {
				type: "generateEAC",
				text: $t('marking_application_form.generate_EAC')
			},
			// 生成简版PDF
			generatePDF: {
				type: "generatePDF",
				text: $t('marking_application_form.simple_pdf')
			},
			// 重置标签订单
			resetLabelOrder: {
				type: "resetLabelOrder",
				text: $t('marking_application_form.reset_label_order')
			},
			// 编辑生产日期
			editDate: {
				type: "editDate",
				text: $t('marking_application_form.edit_date')
			},
			// 编辑厂家名称
			editManufactor: {
				type: "editManufactor",
				text: $t('marking_application_form.edit_manufactor')
			},
			// 编辑外唛数量
			outerMark: {
				type: "outerMark",
				text: $t('marking_application_form.outer_mark')
			},
			// 编辑内唛数量
			innerMark: {
				type: "innerMark",
				text: $t('marking_application_form.inner_mk')
			}
		};
		const batches: MerakXTableDropdown[] = Object.values(batchesConfig);
		return batches;
	});

	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "apply_orders_line_id",
		// 初始化的外部筛选数据
		params,
		toolbar: ["refresh", "setting", ""],
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		// ["selection", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
		columnType: [
			"selection",
			{
				type: "handle",
				width: globalStore.language == "zh" ? 95 : 130,
				slot: "custom_slot_name",
				showHandleDropDown: true
			}
		],
		// awaitParams:true,
	});

	// 给予表格操作权限
	const tableHandler = computed(() => {
		const handlesMap = {
			exportLabelData: {
				type: "exportLabelData",
				text: $t("marking_application_form.export_label_data")
			},
			// 生成EAC版PDF | 下载EAC版PDF
			generateEAC: {
				type: "generateEAC",
				// 生成中 都不显示
				visible: row => {
					console.log(row.pdf_status)
					if (row.pdf_status == 1 || row.pdf_status == 4) {
						return false
					}
					return true
				},
				text: row => {
					// 成功 显示下载EAC版PDF
					if (row.pdf_status == 2) {
						return $t('marking_application_form.download_generate_EAC')
						// 已删除 显示生成EAC版PDF
					} else {
						return $t('marking_application_form.generate_EAC')
					}
				}
			},
			// 生成简版PDF | 下载简版PDF
			generatePDF: {
				type: "generatePDF",
				// 生成中 都不显示
				visible: row => {
					if (row.simple_pdf_status == 1 || row.simple_pdf_status == 4) {
						return false
					}
					return true
				},
				text: row => {
					// 成功 显示下载简版PDF
					if (row.simple_pdf_status == 2) {
						return $t('marking_application_form.download_simple_pdf')
						// 已删除 显示生成简版PDF
					} else {
						return $t('marking_application_form.simple_pdf')
					}
				}
			},
			// 重置标签订单
			resetLabelOrder: {
				type: "resetLabelOrder",
				text: $t('marking_application_form.reset_label_order')
			},
		};
		const handles: MerakXTableDropdown[] = [];

		return Object.values(handlesMap);
	});

	const editorState = reactive < any > ({
		field: '',
		props: {},
		state: false,
	});
	const editForm = reactive({
		num_pages_sscc: '',
		num_pages_km: '',
		production_date_pdf: '',
		factory_name_certify: ''
	})

	// 表格编辑事件
	const handleEditorClick: MerakXTableInstance["onEditor-click"] = (params: any) => {
		editorState.field = params.field;
		editorState.props = params.row;
		editorState.state = true;
		editForm.num_pages_sscc = params.row.num_pages_sscc;
		editForm.num_pages_km = params.row.num_pages_km;
		editForm.production_date_pdf = params.row.production_date_pdf;
		editForm.factory_name_certify = params.row.factory_name_certify;
		apply_orders_line_ids.value = [editorState.props.apply_orders_line_id]
		// 厂家名称，需要请求厂家数据
		console.log(params.field)
		if (params.field === 'factory_name_certify') {
			const obj: any = {
				supplier_id: params.row.supplier_id
			}
			getFactoryNameCertifyAPI(obj).then(({
				code,
				data
			}) => {
				if (code === ResultEnum.SUCCESS) {
					console.log(data.factory_list)
					state.factoryNameCertifyList = data
				}
			})
		}
	};

	// 行内编辑保存
	const apply_orders_line_ids = ref < any > ([])
	const handleSave = () => {
		const obj: any = {
			import_company_id: route.query.i_id,
			apply_orders_line_ids: apply_orders_line_ids.value,
		}
		if (editorState.field === 'production_date_pdf') {
			// 生产日期
			obj.production_date = dayjs(editForm.production_date_pdf).format('YYYY-MM-DD')
		} else if (editorState.field === 'factory_name_certify') {
			// 厂家名称
			obj.factory_id = editForm.factory_name_certify
		} else if (editorState.field === 'num_pages_sscc') {
			// 外唛数量
			obj.num_pages_sscc = editForm.num_pages_sscc
		} else if (editorState.field === 'num_pages_km') {
			// 内唛数量
			obj.num_pages_km = editForm.num_pages_km
		}
		updateFactoryAPI(obj).then(({
			code,
			data
		}) => {
			if (code === ResultEnum.SUCCESS) {
				editorState.state = false;
				tableRef.value?.finishedBatch();
				tableRef.value?.reloadData();
			}
		})
	}

	/**
	 * 表格批量操作事件触发
	 * @param type 同 tablePayload.batched 子项的 type
	 * @param mode 表格选中的模式  current: 当前页  all: 所有页
	 * @param selectedKeys 表格当前页选中模式下选中的行数据 key 的集合, 表格所有页选中模式下未选中的行数据 key 的集合
	 */
	const handleBatchClick: MerakXTableInstance["batchClick"] = async ({
		type,
		mode,
		selectedKeys
	}) => {
		console.log(selectedKeys);
		apply_orders_line_ids.value = selectedKeys
		switch (type) {
			// 批量导出标签数据
			case "exportLabelData":
				// 是否刷新表格, 默认 false, 可选参数
				downloadFunction(params.row,selectedKeys)
				return true;
			// 生成EAC版PDF
			case "generateEAC":
				moreConfirm({
					num: 1,
					msg: $t('marking_application_form.confirm_hint'),
					callback: val => {
						// 根据用户的选择，解决或拒绝Promise
						if (val == 'confirm') {
							const obj1: any = {
								import_company_id: route.query.i_id,
								apply_order_id: route.query.a_id,
								apply_orders_line_ids:selectedKeys,
								is_simple: 0,
							};
							const res1: any = regenerateEADAPI(obj1);
						}
						if (val == 'cancel') {
							
						}
					}
				})
				
				return true;
				// 生成简版PDF
			case "generatePDF":
				moreConfirm({
					num: 1,
					msg: $t('marking_application_form.confirm_hint'),
					callback: val => {
						// 根据用户的选择，解决或拒绝Promise
						if (val == 'confirm') {
							const obj2: any = {
								import_company_id: route.query.i_id,
								apply_order_id: route.query.a_id,
								apply_orders_line_ids:selectedKeys,
								is_simple: 1,
							};
							const res2: any = regenerateEADAPI(obj2)
						}
						if (val == 'cancel') {
							
						}
					}
				})
				return true;
				// 重置标签订单
			case "resetLabelOrder":
				const obj: any = {
					import_company_id: route.query.i_id,
					id: selectedKeys
				}
				const res = await orderResetAPI(obj)
				if (res.code === ResultEnum.SUCCESS) {
					return {
						// 是否刷新表格, 默认 false, 可选参数
						refresh: false,
						// 是否重置表格(分页、排序), 默认 false, 可选参数
						reset: false
					};
				}
				// 编辑生产日期
			case 'editDate':
				editorState.field = 'production_date_pdf';
				editorState.props = {};
				editorState.state = true;
				editForm.production_date_pdf = '';
				break
				// 编辑厂家名称
			case 'editManufactor':
				editorState.field = 'factory_name_certify';
				editorState.props = {};
				editorState.state = true;
				editForm.factory_name_certify = '';
				break
				// 编辑外唛数量
			case 'outerMark':
				editorState.field = 'num_pages_sscc';
				editorState.props = {};
				editorState.state = true;
				editForm.num_pages_sscc = '';
				break
				// 编辑内唛数量
			case 'innerMark':
				editorState.field = 'num_pages_km';
				editorState.props = {};
				editorState.state = true;
				editForm.num_pages_km = '';
				break
			default:
				return;
		}
	};

	/**
	 * 表格操作列事件触发
	 * @param type 同 tablePayload.handles 子项的 type
	 * @param params 表格操作数据, 可结构关于操作行的数据 { row, rowIndex, rowId }
	 */
	const handleHanderClick: MerakXTableInstance["handlerClick"] = async ({
		type,
		params
	}) => {
		switch (type) {
			// 导出标签数据
			case "exportLabelData":
				// 是否刷新表格, 默认 false, 可选参数
				downloadFunction(params.row,[params.row.product_id])
				return true;
				// 生成EAC版PDF | 下载EAC版PDF
			case "generateEAC":
				// 成功 显示下载EAC版PDF
				if (params.row.pdf_status == 2) {
					getPdfLink(params.row, 0)
					// 已删除 显示生成EAC版PDF
				} else {
					// 是否刷新表格, 默认 false, 可选参数
					moreConfirm({
						num: 1,
						msg: $t('marking_application_form.confirm_hint'),
						callback: val => {
							// 根据用户的选择，解决或拒绝Promise
							if (val == 'confirm') {
								const obj1: any = {
									import_company_id: route.query.i_id,
									apply_order_id: params.row.apply_order_id,
									apply_orders_line_ids:[params.row.apply_orders_line_id],
									is_simple: 0,
								};
								const res1: any =  regenerateEADAPI(obj1)
							}
							if (val == 'cancel') {
								
							}
						}
					})
					
					// if (res1.code === ResultEnum.SUCCESS) {
					//   return true;
					// }
				}
				return true;
				// 生成简版PDF | 下载简版PDF
			case "generatePDF":
				// 成功 显示下载简版PDF
				if (params.row.simple_pdf_status == 2) {
					getPdfLink(params.row, 1)
					// 已删除 显示生成简版PDF
				} else {
					// 是否刷新表格, 默认 false, 可选参数
					moreConfirm({
						num: 1,
						msg: $t('marking_application_form.confirm_hint'),
						callback: val => {
							// 根据用户的选择，解决或拒绝Promise
							if (val == 'confirm') {
								const obj2: any = {
									import_company_id: route.query.i_id,
									apply_order_id: params.row.apply_order_id,
									apply_orders_line_ids:[params.row.apply_orders_line_id],
									is_simple: 1,
								};
								const res2: any =  regenerateEADAPI(obj2)
							}
							if (val == 'cancel') {
								
							}
						}
					})
					
					// if (res2.code === ResultEnum.SUCCESS) {
					//   return true;
					// }
				}
				return true;
				// 重置标签订单
			case "resetLabelOrder":
				// 是否刷新表格, 默认 false, 可选参数
				const obj: any = {
					import_company_id: route.query.i_id,
					id: params.row.id
				}
				const res: any = await orderResetAPI(obj)
				// if (res.code === ResultEnum.SUCCESS) {
				//   return true;
				// }
				return true;
			default:
				return;
		}
	};

	//导出excale
	const getPdfLink = (params, type) => {
		let getDataMsg = {
			import_company_id: route.query.i_id,
			apply_order_id: params.apply_order_id,
			is_simple: type,
			sku: params.system_sku || ''
		}
		downloadPdfApi(getDataMsg).then(({
			code,
			data,
			message
		}) => {
			if (code == ResultEnum.SUCCESS) {
				downLoadFile(data.url)
				//defaultStore.downVisable = true; //打开下载列表
			} else {
				ElMessage.error(message)
			}
		});
	}

	//下载模板
	const downLoadFile = (path) => {
		const fileUrl = path; // 文件的URL地址
		const link = document.createElement('a');
		const fileName = path.split("/").slice(-1);
		link.href = fileUrl;
		link.setAttribute('download', fileName);
		link.click();
	}

	//导出excale
	const downloadFunction = (params,arr) => {
		let getDataMsg = {
			route_condition: {
				import_company_id: route.query.i_id,
				apply_order_id: route.query.a_id,
				apply_orders_line_id: arr,
			},
			table_id: tableId.value,
			// 申请单详情
			route_name: 'markings_apply_order_sscc',
		}
		exportTableApi(getDataMsg).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				defaultStore.downVisable = true; //打开下载列表
			}
		});
	}

	// 获取表头数据
	const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
		return getApplicationFormDetailHead({
			import_company_id: route.query.i_id
		}).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				searchRef.value?.getPlanList(data.table_id);
				tableId.value = data.table_id;
				return {
					...data,
					columns: [...data.columns].map(column => {
						switch (column.field) {
							// 左固定 系统货号
							case "system_sku":
								column.fixed = "left";
								return column;
								// 左固定 商家货号
							case "supplier_sku":
								column.fixed = "left";
								return column;
								// 生产日期，厂家名称，外唛数量，内唛数量，可行内编辑
							case "production_date_pdf":
							case "factory_name_certify":
							case "num_pages_km":
							case "num_pages_sscc":
								column.params = {
									editor: true
								};
								return column;
							case "pdf":
								column.slots = {
									default: "pdf"
								};
								return column
							case "outter_mark":
								column.slots = {
									default: "outter_mark"
								};
								return column
							default:
								return column;
						}
					})
				};
			}
		});
	};

	/**
	 * 获取表格数据
	 * @param page 分页参数
	 * @param sorts 多重排序参数
	 * @param filters 表头筛选参数
	 * @param from 外部由 tablePayload.params 传入的自定义参数
	 */
	const queryData: MerakXTableInstance["queryData"] = async ({
		page,
		sorts,
		from
	}) => {
		// 创建请求表格数据的参数
		const params: Record < string, any > = {};
		// 如果有分页数据
		if (!!page) {
			Object.assign(params, {
				...page
			});
		}
		// 如果有排序数据
		if (!!sorts) {
			for (let sort of sorts.values()) {
				console.log(sort);
			}
		}
		// 如果有自定义参数
		if (!!from) {
			for (let key of Object.keys(from)) {
				const item = from[key];
				!!item && (params[key] = item);
			}
		}
		params.import_company_id = route.query.i_id;
		params.apply_order_id = route.query.a_id;
		// delete params.pageSize;
		// delete params.currentPage;
		// 初始化接口需要传入队列 loading 暴露的 id
		return getApplicationFormDetailList(params).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				return data.table_data;
			}
		});
	};
	const cancenForm = async (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		model.value = false;
	};

	const submitForm = async (formEl: FormInstance | undefined, isHide: boolean) => {
		if (!formEl) return;
		await formEl.validate((valid, fields) => {
			//failMsg('所有的属性值(中文)、属性值(俄文)不能为空')
			if (valid) {
				let postData = ruleForm;
				if (countryId.value != "") {
					postData.manufacturer_county_id = countryId.value;
				}

				// addCountryItem(postData).then(({ code, data,message }) => {
				// 	if (code == 2000) {
				// 		formEl.resetFields();
				// 		ruleForm.sort = "999";
				// 		ruleForm.manufacturer_county_ru = "";
				// 		ruleForm.manufacturer_county_cn = "";
				// 		countryId.value = "";
				// 		tableRef.value?.reloadData();
				// 		model.value = false;
				// 		// successMsg(proxy!.$t("goods_attribute.add_success"));
				// 		// formEl.resetFields();
				// 		// ruleForm.prop_sort_detail = "";
				// 		// ruleForm.prop_sort_filter = "";
				// 		// ruleForm.sort_prop_detail_focal = "";
				// 		// tableConfig.tableData = [];
				// 		// state.refresh = true;
				// 		// if(!isHide){
				// 		// 	emit('close',state.refresh)
				// 		// }
				// 	} else {
				// 		failMsg(message)
				// 	}
				// })
			} else {
				console.log("error submit!", fields);
			}
		});
	};
	const handleResetSearch = () => {
		Object.keys(ruleForm).map(item => {
			if (item == "created_at") {
				ruleForm[item] = [];
			} else {
				ruleForm[item] = "";
			}
		});
		state.thisPageDate = {
			...state.thisPageDate,
			...ruleForm
		};
		searchRef.value?.clear();
		searchRef.value?.modalHide();
	};
	const handleSearch = () => {
		state.thisPageDate = {
			...state.thisPageDate,
			...ruleForm
		};
		searchRef.value?.clear();
		searchRef.value?.modalHide();
		//  searchRef.value?.valid()?.then(() => {
		//    searchState.search = undefined;
		// console.log(ruleForm.value)
		//    //searchState.params = { ...searchFormValue.value };
		// console.log(searchRef.value)
		//    // 清空外部搜索
		//    searchRef.value?.clear();
		//    // 关闭高级搜索弹窗
		//    searchRef.value?.modalHide();
		//  });
	};
	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {

		if (params.action === "plan" && !!params.params) {
			for (let key of Object.keys(ruleForm)) {
				ruleForm[key] = '';
			}
			for (let key of Object.keys(params.params)) {
				if (!key.includes("_options")) {
					ruleForm[key] = params.params[key];
				}
			}
		}

		state.thisPageDate = {
			...state.thisPageDate,
			...ruleForm
		};
		state.thisPageDate.keyword = params.search;


	};

	//打开搜索方案弹出
	const searchbar = ref < any > ();
	const showPlanModal = () => {
		searchbar.value.showPlanModal();
	};

	const init = async () => {
		//queryStatData();
		getUserAuth("producingCountry").then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				countryAuth.value = data;
			}
		});
		// 获取高级搜索中 订单状态 option 数据
		getFactoryNameCertifyAPI().then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				state.factoryNameCertifyOptions = data as any
			}
		});
	};
	const addCountry = () => {
		model.value = true;
		countryId.value = "";
		ruleForm.sort = "999";
		ruleForm.manufacturer_county_ru = "";
		ruleForm.manufacturer_county_cn = "";
	};

	const goEdit = row => {
		model.value = true;
		countryId.value = row.manufacturer_county_id;
		ruleForm.sort = row.sort;
		ruleForm.manufacturer_county_ru = row.manufacturer_county_ru;
		ruleForm.manufacturer_county_cn = row.manufacturer_county_cn;
	};
	const goDelete = row => {
		let data = {
			manufacturer_county_id: row.manufacturer_county_id
		};
		ElMessageBox.confirm(proxy!.$t("archive_set_producingCountry.country_warning"), proxy!.$t("merak.tip_modal"), {
			confirmButtonText: proxy!.$t("merak.confirm"),
			cancelButtonText: proxy!.$t("merak.cancel"),
			type: "warning"
		}).then(() => {
			// deleteCountryItem(data).then(({ code, data,message }) => {
			// 	if (code == 2000) {
			// 		tableRef.value?.reloadData();
			// 		successMsg(proxy!.$t("merak.delete_success"));
			// 	} else {
			// 		failMsg(message)
			// 	}
			// })
		});
	};

	onMounted(() => {
		init();
	});
</script>

<style type="text/css" scoped>
	@import "./index.scss";
</style>